{% extends 'work-layout.html' %}
{% block form-index %}nav-link{% endblock %}
{% block form-show %}show{% endblock %}
{% block form-index-llmPHQ-9 %}active{% endblock %}
{% block body %}

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<main id="main" class="main">

   <div class="modal fade" id="declarationModal" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false">
    <div class="modal-dialog modal-dialog-centered modal-lg">
      <div class="modal-content">
        <div class="modal-header bg-primary text-white">
          <h5 class="modal-title"><i class="bi bi-exclamation-circle me-2"></i>测评声明</h5>
        </div>
        <div class="modal-body" style="max-height: 60vh; overflow-y: auto;">
          <h5 class="text-danger mb-3">请仔细阅读以下声明：</h5>
          <ol class="lead">
            <li class="mb-3">本测评工具基于PHQ-9抑郁筛查量表开发，结果仅供参考，不能作为临床诊断依据</li>
            <li class="mb-3">您的所有回答将被加密存储，仅用于生成测评报告，我们承诺保护您的隐私安全</li>
            <li class="mb-3">建议在安静环境下独立完成测评，回答过程大约需要3-5分钟</li>
            <li class="mb-3">如果您感到任何不适，可以随时中止测评并联系专业心理咨询师</li>
            <li class="text-danger">根据相关法规要求，您需要仔细阅读本声明满5秒后方可开始测评</li>
          </ol>
        </div>
        <div class="modal-footer">
          <button type="button" id="agreeButton" class="btn btn-lg btn-primary" disabled>
            同意（5秒）
          </button>
        </div>
      </div>
    </div>
  </div>

  <div class="pagetitle">
    <h1>AI心理助手</h1>
    <nav>
      <ol class="breadcrumb">
        <li class="breadcrumb-item"><a href="/">主页</a></li>
        <li class="breadcrumb-item"><a href="/">工具箱</a></li>
        <li class="breadcrumb-item active">小帕-心理树洞-PHQ-9
</li>
      </ol>
    </nav>
  </div>

  <section class="section">
    <div class="row">
      <div class="col-lg-2"></div>
      <div class="col-lg-8">
        <div class="card">
          <div class="card-body">
            <div class="d-flex justify-content-between align-items-center mb-3">
              <h5 class="card-title">对话窗口</h5>
              <form method="post" class="mb-0">

                <button type="submit" name="reset" class="btn btn-sm btn-outline-danger">
                  清空历史
                </button>
              </form>
            </div>

            <!-- 消息容器 -->
            <div id="chat-container" class="border rounded p-3 mb-3"
                 style="height: 60vh; overflow-y: auto; background-color: #f8f9fa;">
              {% for message in chat_history %}
                <div class="message-wrapper mb-3">
                  <div class="card {% if message.role == 'user' %}bg-primary text-white ml-auto{% else %}bg-light{% endif %}"
                       style="max-width: 85%;">
                    <div class="card-body p-3">
                      <div class="message-content">{{ message.content|linebreaks }}</div>
                      <small class="d-block mt-2 text-end opacity-75">
                        {% if message.role == 'user' %}您{% else %}助手{% endif %}
                        <span class="ms-2">{{ forloop.counter }}</span>
                      </small>
                    </div>
                  </div>
                </div>
              {% endfor %}
            </div>

            <!-- 输入表单 -->
            <form id="chat-form" method="post">
              {% csrf_token %}
              <div class="input-group">
                <textarea id="user-input" name="message"
                          class="form-control"
                          placeholder="请输入内容。。。"
                          rows="2"
                          required
                          {% if phq9_complete %} disabled {% endif %}
                ></textarea>
                <button type="submit" class="btn btn-primary px-4">
                  <i class="bi bi-send"></i> 发送
                </button>
              </div>
              <small class="text-muted mt-1 d-block">支持Shift+Enter换行</small>
            </form>
          </div>
        </div>
      </div>
      <div class="col-lg-2"></div>
    </div>
  </section>
</main>

<style>

  /* 新增模态框样式 */
#declarationModal .modal-header {
  border-bottom: 2px solid #dee2e6;
}
#declarationModal .modal-body ol {
  counter-reset: item;
  padding-left: 1.5rem;
}
#declarationModal .modal-body li {
  font-size: 1.1rem;
  line-height: 1.6;
  padding-left: 1rem;
  border-left: 3px solid #0d6efd;
  margin-bottom: 1.5rem;
}
/* 自定义样式 */
#chat-container::-webkit-scrollbar {
  width: 8px;
}
#chat-container::-webkit-scrollbar-track {
  background: #f1f1f1;
}
#chat-container::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 4px;
}

.typing-indicator {
  display: inline-flex;
  padding: 8px 15px;
  background: #e9ecef;
  border-radius: 20px;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

.message-wrapper {
  transition: opacity 0.3s ease;
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
  // 初始化模态框
  const declarationModal = new bootstrap.Modal(document.getElementById('declarationModal'), {
    backdrop: 'static',
    keyboard: false
  });
  declarationModal.show();

  // 倒计时逻辑
  let seconds = 5;
  const agreeButton = document.getElementById('agreeButton');
  const updateButton = () => {
    agreeButton.textContent = `同意（${seconds}秒）`;
    if (seconds <= 0) {
      agreeButton.disabled = false;
      agreeButton.textContent = '同意并开始测评';
      clearInterval(timer);
    }
    seconds--;
  };
  const timer = setInterval(updateButton, 1000);
  updateButton(); // 立即执行一次

  // 同意按钮点击处理
  agreeButton.addEventListener('click', () => {
    declarationModal.hide();
    // 启用输入框（如果被禁用）
    document.getElementById('user-input').disabled = false;
  });
});

document.addEventListener('DOMContentLoaded', () => {
  const chatContainer = document.getElementById('chat-container');
  const form = document.getElementById('chat-form');
  let currentAssistantMsg = null;
  let isStreaming = false;

  // 自动滚动
  function scrollToBottom() {
    chatContainer.scrollTop = chatContainer.scrollHeight;
  }

  // 显示打字状态
  function showTyping() {
    const indicator = document.createElement('div');
    indicator.className = 'typing-indicator mb-3';
    indicator.innerHTML = `
      <div class="d-flex align-items-center">
        <div class="spinner-grow spinner-grow-sm text-secondary me-2"></div>
        <span class="text-muted">思考中...</span>
      </div>
    `;
    chatContainer.appendChild(indicator);
    scrollToBottom();
    return indicator;
  }

  // 处理流式响应
  async function handleStream(response) {
    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let buffer = '';

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      buffer += decoder.decode(value, { stream: true });
      const parts = buffer.split('\n');

      buffer = parts.pop(); // 保留未完成部分

      for (const part of parts) {
        if (!part) continue;
        try {
          const data = JSON.parse(part);

          if (data.error) {
            alert(data.error);
            return;
          }

          if (data.finished) {
            currentAssistantMsg = null;
            isStreaming = false;
            if (data.phq9_complete) {
              document.getElementById('user-input').disabled = true;
              document.getElementById('complete-section').style.display = 'block';
            }
            return;
          }

          if (!currentAssistantMsg) {
            currentAssistantMsg = document.createElement('div');
            currentAssistantMsg.className = 'message-wrapper mb-3';
            currentAssistantMsg.innerHTML = `
              <div class="card bg-light" style="max-width: 85%;">
                <div class="card-body p-3">
                  <div class="message-content"></div>
                  <small class="d-block mt-2 text-end opacity-75">
                    助手
                  </small>
                </div>
              </div>
            `;
            chatContainer.appendChild(currentAssistantMsg);
          }

          const contentDiv = currentAssistantMsg.querySelector('.message-content');
          contentDiv.innerHTML += data.content.replace(/\n/g, '<br>');
          scrollToBottom();
        } catch (e) {
          console.error('解析错误:', e);
        }
      }
    }
  }

  // 表单提交
  form.addEventListener('submit', async (e) => {
    e.preventDefault();


    if (isStreaming || document.getElementById('user-input').disabled) {
      alert('测评已完成，请查看结果');
      return;
    }

    if (isStreaming) return;


    const input = document.getElementById('user-input');
    const message = input.value.trim();
    if (!message) return;

    // 添加用户消息
    const userMsg = document.createElement('div');
    userMsg.className = 'message-wrapper mb-3';
    userMsg.innerHTML = `
      <div class="card bg-primary text-white ml-auto" style="max-width: 85%;">
        <div class="card-body p-3">
          <div class="message-content">${message.replace(/\n/g, '<br>')}</div>
          <small class="d-block mt-2 text-end opacity-75">
            您
          </small>
        </div>
      </div>
    `;
    chatContainer.appendChild(userMsg);
    input.value = '';
    scrollToBottom();

    // 显示加载状态
    const typingIndicator = showTyping();
    isStreaming = true;

    try {
      const response = await fetch(form.action, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'X-Requested-With': 'XMLHttpRequest'
        },
        body: new URLSearchParams({
          message: message,
          csrfmiddlewaretoken: form.querySelector('[name=csrfmiddlewaretoken]').value
        })
      });

      typingIndicator.remove();
      if (!response.ok) throw new Error(`HTTP错误: ${response.status}`);
      await handleStream(response);
    } catch (error) {
      console.error('请求失败:', error);
      alert('请求失败，请检查网络连接');
      isStreaming = false;
    }
  });

  // 调整输入框高度
  const textarea = document.getElementById('user-input');
  textarea.addEventListener('input', () => {
    textarea.style.height = 'auto';
    textarea.style.height = textarea.scrollHeight + 'px';
  });

  // 初始化滚动
  scrollToBottom();
});
</script>

{% endblock %}